package com.gizwits.javautil;


import jodd.util.Bits;


import java.util.BitSet;


public class utils {
    public static BitSet fromByte(byte b)
    {
        BitSet bits = new BitSet(8);
        for (int i = 0; i < 8; i++)
        {
            bits.set(i, (b & 1) == 1);
            b >>= 1;
        }
        return bits;
    }
    public static byte bit2byte(String bString){
        byte result=0;
        for(int i=bString.length()-1,j=0;i>=0;i--,j++){
            result+=(Byte.parseByte(bString.charAt(i)+"")*Math.pow(2, j));
        }
        return result;
    }
    public static String byte2bits(byte b) {
        int z = b;
        z |= 256; //使最后能有8位供截取，而又不影响byte的原来值。
        String str = Integer.toBinaryString(z);
        int len = str.length();
        return str.substring(len-8, len);
    }
     public  static   int  byte2bool(byte[] src, int offset){

           if (Bits.getBoolean(src,offset)){
                return  1;
           }
           return 0;

     }
    //将uint变量分解为四个字节。低位在前。
    public static int bytesToUint32(byte[] data, int offset) {
        return (data[offset] << 24) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3];
    }

    public static int bytesToUint8(byte[] data, int offset) {
        return  (data[offset + 0] << 8) + data[offset + 1];
    }

    public static String bytes2Hex(byte[] src){
        char[] res = new char[src.length*2];
        final char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        for(int i=0,j=0; i<src.length; i++){
            res[j++] = hexDigits[src[i] >>>4 & 0x0f];
            res[j++] = hexDigits[src[i] & 0x0f];
        }

        return new String(res);
    }

}
